// 主题切换
const btnTheme = document.getElementById('toggle-theme');
btnTheme?.addEventListener('click', () => {
  const dark = document.documentElement.classList.toggle('dark');
  document.documentElement.style.colorScheme = dark ? 'dark' : 'light';
});

// 环境监测模拟
const envTempEl = document.getElementById('env-temp');
const envHumEl = document.getElementById('env-hum');
const envPmEl = document.getElementById('env-pm');
const barTemp = document.getElementById('bar-temp');
const barHum = document.getElementById('bar-hum');
const barPm = document.getElementById('bar-pm');
const chips = document.getElementById('env-chips');

function randRange(min, max) { return Math.round((Math.random() * (max - min) + min) * 10) / 10; }
function setChip(text, level) {
  const span = document.createElement('span');
  span.className = `chip ${level}`;
  span.textContent = text;
  return span;
}

function updateEnv() {
  const temp = randRange(18, 30);
  const hum = randRange(25, 65);
  const pm = Math.round(randRange(10, 110));
  envTempEl.textContent = `${temp.toFixed(1)}°C`;
  envHumEl.textContent = `${hum.toFixed(1)}%`;
  envPmEl.textContent = `${pm} μg/m³`;
  barTemp.style.width = `${(temp - 10) / 30 * 100}%`;
  barHum.style.width = `${hum}%`;
  barPm.style.width = `${pm / 150 * 100}%`;
  chips.innerHTML = '';
  chips.append(setChip(temp < 26 ? '温度适宜' : '温度偏高', temp < 26 ? 'good' : 'warn'));
  chips.append(setChip(hum > 35 ? '湿度正常' : '湿度偏低', hum > 35 ? 'good' : 'warn'));
  chips.append(setChip(pm <= 35 ? '空气优' : pm <= 75 ? '空气良' : '污染警告', pm <= 35 ? 'good' : pm <= 75 ? 'warn' : 'bad'));
}
setInterval(updateEnv, 2200);
updateEnv();

// 用药管理本地存储
const medForm = document.getElementById('med-form');
const medSummary = document.getElementById('med-summary');
const medRemind = document.getElementById('med-reminders');
const btnLoadPlan = document.getElementById('loadPlan');

function formatPlanSummary(plan) {
  return `药品：${plan.drugName}，剂量：${plan.dose}${plan.unit}，间隔：${plan.intervalHours}小时，起始：${plan.startTime}`;
}
function computeReminders(startTime, intervalHours) {
  const [sh, sm] = startTime.split(':').map(Number);
  const start = new Date(); start.setHours(sh, sm, 0, 0);
  const out = [];
  for (let t = new Date(start); t.getDate() === start.getDate(); t = new Date(t.getTime() + intervalHours * 3600 * 1000)) {
    out.push(`${String(t.getHours()).padStart(2, '0')}:${String(t.getMinutes()).padStart(2, '0')}`);
    if (out.length > 10) break; // 安全保护
  }
  return out;
}
function renderReminders(reminders) {
  medRemind.innerHTML = '';
  if (!reminders.length) return;
  reminders.forEach(r => {
    const pill = document.createElement('div');
    pill.className = 'pill';
    pill.textContent = `今日提醒：${r}`;
    medRemind.append(pill);
  });
}
function loadPlan() {
  try {
    const raw = localStorage.getItem('medication_plan');
    if (!raw) return;
    const plan = JSON.parse(raw);
    document.getElementById('drugName').value = plan.drugName;
    document.getElementById('dose').value = plan.dose;
    document.getElementById('unit').value = plan.unit;
    document.getElementById('interval').value = plan.intervalHours;
    document.getElementById('startTime').value = plan.startTime;
    medSummary.textContent = formatPlanSummary(plan);
    renderReminders(computeReminders(plan.startTime, Number(plan.intervalHours)));
  } catch {}
}
medForm?.addEventListener('submit', (e) => {
  e.preventDefault();
  const plan = {
    drugName: document.getElementById('drugName').value.trim(),
    dose: Number(document.getElementById('dose').value),
    unit: document.getElementById('unit').value.trim(),
    intervalHours: Number(document.getElementById('interval').value),
    startTime: document.getElementById('startTime').value
  };
  if (!plan.drugName || !plan.unit || isNaN(plan.dose) || isNaN(plan.intervalHours) || !/^\d{2}:\d{2}$/.test(plan.startTime)) {
    medSummary.textContent = '请完整填写：药品/剂量/单位/间隔小时/开始时间(如 08:30)';
    return;
  }
  localStorage.setItem('medication_plan', JSON.stringify(plan));
  medSummary.textContent = formatPlanSummary(plan);
  renderReminders(computeReminders(plan.startTime, plan.intervalHours));
});
btnLoadPlan?.addEventListener('click', loadPlan);
loadPlan();

// 跌倒检测模拟
const fallDot = document.getElementById('fall-dot');
const fallText = document.getElementById('fall-text');

document.querySelectorAll('#fall-card button[data-fall]').forEach(btn => {
  btn.addEventListener('click', () => {
    const mode = btn.getAttribute('data-fall');
    if (mode === 'normal') { fallDot.className = 'dot'; fallText.textContent = '状态：未检测到跌倒'; }
    if (mode === 'suspected') { fallDot.className = 'dot warn'; fallText.textContent = '状态：疑似跌倒，确认中…'; }
    if (mode === 'confirmed') { fallDot.className = 'dot bad'; fallText.textContent = '状态：已确认跌倒，正在告警！'; }
  });
});

// 简易话疗（接入 DeepSeek API，失败时离线兜底）
const chatBox = document.getElementById('chat-box');
const chatInput = document.getElementById('chat-input');
const chatSend = document.getElementById('chat-send');
const chatMic = document.getElementById('chat-mic');

// 语音输入（Web Speech API）
const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
let recognizer = null;
let recognizing = false;
function stopMicUI() {
  recognizing = false;
  chatMic?.classList.remove('recording');
  if (chatInput) chatInput.placeholder = '输入你的话…';
}
if (SR) {
  recognizer = new SR();
  recognizer.lang = 'zh-CN';
  recognizer.interimResults = true;
  recognizer.continuous = false;
  recognizer.onstart = () => { recognizing = true; chatMic?.classList.add('recording'); if (chatInput) chatInput.placeholder = '正在聆听…'; };
  recognizer.onerror = (e) => { console.warn('Speech error', e); stopMicUI(); };
  recognizer.onend = () => { const t = chatInput?.value?.trim(); stopMicUI(); if (t) chatSend?.click(); };
  recognizer.onresult = (ev) => {
    let text = '';
    for (let i = ev.resultIndex; i < ev.results.length; i++) { text += ev.results[i][0].transcript; }
    if (chatInput) chatInput.value = text.trim();
  };
}
chatMic?.addEventListener('click', () => {
  if (!SR || !recognizer) { pushBubble('当前浏览器不支持语音识别', 'bot'); return; }
  if (!recognizing) { try { recognizer.start(); } catch (e) { console.warn('start error', e); } }
  else { try { recognizer.stop(); } catch (e) { console.warn('stop error', e); } }
});

function pushBubble(text, who = 'me') {
  const div = document.createElement('div');
  div.className = `bubble ${who}`;
  div.textContent = text;
  chatBox.append(div);
  chatBox.scrollTop = chatBox.scrollHeight;
}
function botReplyFallback(userText) {
  const lowers = (userText || '').toLowerCase();
  let reply = '我听到了，也一直在陪你～';
  if (lowers.includes('孤独') || lowers.includes('难过')) reply = '抱抱你～想不想一起做个舒缓呼吸练习？';
  if (lowers.includes('吃药')) reply = '好的，记得按计划服药，我可以帮你提醒。';
  if (lowers.includes('运动')) reply = '太棒了！我们今天试试轻柔拉伸，5分钟就好～';
  setTimeout(() => pushBubble(reply, 'bot'), 500);
}
async function sendToLLM(text) {
  try {
    const res = await fetch('/api/chat', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ message: text })
    });
    if (!res.ok) return null;
    const data = await res.json();
    return data.reply || null;
  } catch {
    return null;
  }
}
chatSend?.addEventListener('click', async () => {
  const text = chatInput.value.trim();
  if (!text) return;
  pushBubble(text, 'me');
  chatInput.value = '';
  const reply = await sendToLLM(text);
  if (reply) pushBubble(reply, 'bot'); else botReplyFallback(text);
});
chatInput?.addEventListener('keydown', (e) => { if (e.key === 'Enter') chatSend.click(); });